package com.usian.common.exception;

import com.usian.model.common.dtos.ResponseResult;
import lombok.extern.log4j.Log4j2;
import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author szx
 * @date 2022/10/10
 * @description 自定义异常进行通用返回
 */

/*@ControllerAdvice// 控制器增强注解*/
@RestControllerAdvice
@Log4j2
public class ExceptionCatch {

    // Key  value
    public static ImmutableMap<Class<? extends Throwable>,ResponseResult> EXCEPTIONS;
    public static ImmutableMap.Builder<Class<? extends Throwable>,ResponseResult> builder = EXCEPTIONS.builder();

    static {
        builder.put(IndexOutOfBoundsException.class,ResponseResult.errorResult(20006,"集合或数组超过了限制！"));
        builder.put(NullPointerException.class,ResponseResult.errorResult(20007,"对象不能为空！"));
        builder.put(ArithmeticException.class,ResponseResult.errorResult(20008,"除数不能为0！"));
    }

    //所有controller运行 他都能获取到

    /* @ResponseBody*/

    //异常处理器 与上面注解ControllerAdvice一起使用，可以拦截指定的异常信息
    @ExceptionHandler(value = {ConsumerException.class})
    public ResponseResult consumerException(ConsumerException e){
        log.error("捕获自定义异常!"+e.getMessage());
        return e.getResult();
    }


    @ExceptionHandler(value = {Exception.class})
    public ResponseResult CustomException(Exception e){
        // 1. 先维护常用的异常类型
        // 2. 根据异常类型获取 值
        // 3. 如果有直接返回
        // 4. 如果没有 在返回99999
        log.error("ALL Exception:"+e.getMessage());
        e.printStackTrace();
        if(EXCEPTIONS == null){
            EXCEPTIONS = builder.build();
        }
        // 根据异常类型 取值
        ResponseResult responseResult =  EXCEPTIONS.get(e.getClass());
        if(responseResult!=null){
            return responseResult;
        }
        // 处理异常   99999
        return ResponseResult.errorResult(99999,"出现不可预知异常！");
    }



}
